//
//  NewsViewController.m
//  BasketballClub
//
//  Created by 孙鸿吉 on 16/1/6.
//  Copyright © 2016年 孙鸿吉. All rights reserved.
//

#import "NewsViewController.h"
#import "NewsView.h"
#import "NewsHandle.h"
#import "NewsModel.h"
#import "NewsTableViewCell.h"
#import "NewsShowViewController.h"
#import <MJRefresh.h>
#import <AVOSCloud.h>
#import "CoreDataManager.h"
@interface NewsViewController ()<UITableViewDataSource,UITableViewDelegate,UIScrollViewDelegate>
@property(nonatomic,strong)NewsView *newsView;
@property(nonatomic,strong)NewsModel *model;
@property (nonatomic,assign)NSInteger npcNumber;

@end

@implementation NewsViewController
//替换根视图
-(void)loadView{
    
    self.newsView = [[NewsView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.view = self.newsView;
    
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.npcNumber = 0;
    
    //下拉刷新
    [self updateData];
    [self updateCBA];
    //上拉加载
    [self addData1];
    
    //隐藏导航栏
    [[self navigationController] setNavigationBarHidden:YES animated:YES];
    
    //设置代理
    self.newsView.scrollview.delegate = self;
    self.newsView.newsCBATableView.delegate = self;
    self.newsView.newsNBATableView.delegate = self;
    self.newsView.newsCBATableView.dataSource = self;
    self.newsView.newsNBATableView.dataSource = self;
    
    //置顶btn
    [self.newsView.btn_top addTarget:self action:@selector(btn_topAction:) forControlEvents:UIControlEventTouchUpInside];
    
    //注册重用标识
    [self.newsView.newsNBATableView registerClass:[NewsTableViewCell class] forCellReuseIdentifier:@"NewsTableViewCell"];
    [self.newsView.newsCBATableView registerClass:[NewsTableViewCell class] forCellReuseIdentifier:@"NewsTableViewCell"];
    //NBA CBA 点击事件
    [self.newsView.leftButton addTarget:self action:@selector(NBABtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.newsView.rightButton addTarget:self action:@selector(CBABtnAction:) forControlEvents:UIControlEventTouchUpInside];
    
    
}
//置顶按钮
-(void)btn_topAction:(UIButton *)sender
{
    //根据tableview偏移量 实现置顶
    [self.newsView.newsNBATableView setContentOffset:CGPointMake(0, 0) animated:YES];
    [self.newsView.newsCBATableView setContentOffset:CGPointMake(0, 0) animated:YES];
    //点击之后隐藏btn_top
    self.newsView.btn_top.hidden = YES;
    
}


#pragma mark --- NBA滚时监听
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    //如果scrollview偏移量为0
    if (self.newsView.scrollview.contentOffset.x == 0) {
        //设置scrollview的显示frame
        [self.newsView.scrollview setContentOffset:CGPointMake(0, -20*LAYOUT_SIZE_HEIGHT) animated:YES];
        //根据scrollview偏移量 改变NBA CBA按钮的状态
        self.newsView.leftButton.tintColor = [UIColor yellowColor];
        self.newsView.leftButton.titleLabel.font = [UIFont systemFontOfSize:30*LAYOUT_SIZE];
        self.newsView.rightButton.tintColor = [UIColor whiteColor];
        self.newsView.rightButton.titleLabel.font = [UIFont systemFontOfSize:26*LAYOUT_SIZE];
        //如果tableview的高度偏移量大于一个屏幕 显示置顶按钮 否则隐藏
        if (self.newsView.newsNBATableView.contentOffset.y > [UIScreen mainScreen].bounds.size.height) {
            self.newsView.btn_top.hidden = NO;
        } else {
            self.newsView.btn_top.hidden = YES;
        }
    }
    //如果scrollview偏移量为一个屏幕宽
    if (self.newsView.scrollview.contentOffset.x == [UIScreen mainScreen].bounds.size.width) {
        //设置scrollview的显示frame
        [self.newsView.scrollview setContentOffset:CGPointMake(414*LAYOUT_SIZE, -20*LAYOUT_SIZE_HEIGHT) animated:YES];
        //根据scrollview偏移量 改变NBA CBA按钮的状态
        self.newsView.leftButton.tintColor = [UIColor whiteColor];
        self.newsView.rightButton.tintColor = [UIColor yellowColor];
        self.newsView.rightButton.titleLabel.font = [UIFont systemFontOfSize:30*LAYOUT_SIZE];
        self.newsView.leftButton.titleLabel.font = [UIFont systemFontOfSize:26*LAYOUT_SIZE];
        //如果tableview的高度偏移量大于一个屏幕 显示置顶按钮 否则隐藏
        if (self.newsView.newsCBATableView.contentOffset.y > [UIScreen mainScreen].bounds.size.height) {
            self.newsView.btn_top.hidden = NO;
        } else {
            self.newsView.btn_top.hidden = YES;
        }
    }
}

#pragma mark --- NBA滚完监听 具体注释如上滚时监听
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    //如果scrollview偏移量为0
    if (self.newsView.scrollview.contentOffset.x == 0) {
        //设置scrollview的显示frame
        [self.newsView.scrollview setContentOffset:CGPointMake(0, -20*LAYOUT_SIZE_HEIGHT) animated:YES];
        self.newsView.leftButton.tintColor = [UIColor yellowColor];
        self.newsView.leftButton.titleLabel.font = [UIFont systemFontOfSize:30*LAYOUT_SIZE];
        self.newsView.rightButton.tintColor = [UIColor whiteColor];
        self.newsView.rightButton.titleLabel.font = [UIFont systemFontOfSize:26*LAYOUT_SIZE];
        if (self.newsView.newsNBATableView.contentOffset.y > [UIScreen mainScreen].bounds.size.height) {
            self.newsView.btn_top.hidden = NO;
        } else {
            self.newsView.btn_top.hidden = YES;
        }
    }
    if (self.newsView.scrollview.contentOffset.x == [UIScreen mainScreen].bounds.size.width) {
        [self.newsView.scrollview setContentOffset:CGPointMake(414*LAYOUT_SIZE, -20*LAYOUT_SIZE_HEIGHT) animated:YES];
        self.newsView.leftButton.tintColor = [UIColor whiteColor];
        self.newsView.rightButton.tintColor = [UIColor yellowColor];
        self.newsView.rightButton.titleLabel.font = [UIFont systemFontOfSize:30*LAYOUT_SIZE];
        self.newsView.leftButton.titleLabel.font = [UIFont systemFontOfSize:26*LAYOUT_SIZE];
        if (self.newsView.newsCBATableView.contentOffset.y > [UIScreen mainScreen].bounds.size.height) {
            self.newsView.btn_top.hidden = NO;
        } else {
            self.newsView.btn_top.hidden = YES;
        }
    }
    
}

//NBA 点击实现
-(void)NBABtnAction:(UIButton *)sender
{
    //点击改变字体跟颜色
    [self.newsView.scrollview setContentOffset:CGPointMake(0, -20*LAYOUT_SIZE_HEIGHT) animated:YES];
    self.newsView.leftButton.tintColor = [UIColor yellowColor];
    self.newsView.leftButton.titleLabel.font = [UIFont systemFontOfSize:30*LAYOUT_SIZE];
    self.newsView.rightButton.tintColor = [UIColor whiteColor];
    self.newsView.rightButton.titleLabel.font = [UIFont systemFontOfSize:26*LAYOUT_SIZE];
    
}
//CBA 点击实现
-(void)CBABtnAction:(UIButton *)sender
{
    //点击改变字体跟颜色
    [self.newsView.scrollview setContentOffset:CGPointMake(414*LAYOUT_SIZE, -20*LAYOUT_SIZE_HEIGHT) animated:YES];
    self.newsView.leftButton.tintColor = [UIColor whiteColor];
    self.newsView.rightButton.tintColor = [UIColor yellowColor];
    self.newsView.rightButton.titleLabel.font = [UIFont systemFontOfSize:30*LAYOUT_SIZE];
    self.newsView.leftButton.titleLabel.font = [UIFont systemFontOfSize:26*LAYOUT_SIZE];
    
}

#pragma mark ---设置cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell;
    //如果是NBA的tableview
    if (tableView == self.newsView.newsNBATableView) {
        NewsTableViewCell *cell = [self.newsView.newsNBATableView dequeueReusableCellWithIdentifier:@"NewsTableViewCell"];
        NewsModel *nbamodel = [NewsHandle sharedNewsHandle].dataArray[indexPath.row];
        [cell setNewsModel:nbamodel];
        //当喜欢次数为零 隐藏喜欢
        NSInteger nbanum = [self.model.likecount integerValue];
        if (nbanum == 0) {
            cell.likeLabel.hidden = YES;
        }
        
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        //初次加载从LeanCloud里面拿出阅读人数赋值到cell上
        NSString *readCount = [NSString stringWithFormat:@"newsReadCount%ld",indexPath.row];
        AVQuery *query = [AVQuery queryWithClassName:@"News"];
        [query getFirstObjectInBackgroundWithBlock:^(AVObject *object, NSError *error) {
            NSInteger number = [[object objectForKey:readCount]integerValue];
            NSInteger num = [nbamodel.readarts integerValue];
            cell.readLabel.text = [NSString stringWithFormat:@"%ld",num + number];
        }];
        return cell;
    }
    //如果是CBA的tableview
    if (tableView == self.newsView.newsCBATableView) {
        NewsTableViewCell *cell = [self.newsView.newsCBATableView dequeueReusableCellWithIdentifier:@"NewsTableViewCell"];
        NewsModel *cbamodel = [NewsHandle sharedNewsHandle].CBAarray[indexPath.row];
        [cell setNewsModel:cbamodel];
        //当喜欢次数为零 隐藏喜欢
        NSInteger cbanum = [self.model.likecount integerValue];
        if (cbanum == 0) {
            cell.likeLabel.hidden = YES;
        }
        
        [cell setNewsModel:cbamodel];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        
        //    初次加载从LeanCloud里面拿出阅读人数赋值到cell上
        NSString *readCount = [NSString stringWithFormat:@"newsReadCount%ld",indexPath.row];
        AVQuery *query = [AVQuery queryWithClassName:@"CBANews"];
        [query getFirstObjectInBackgroundWithBlock:^(AVObject *object, NSError *error) {
            NSInteger number = [[object objectForKey:readCount]integerValue];
            NSInteger num = [cbamodel.readarts integerValue];
            cell.readLabel.text = [NSString stringWithFormat:@"%ld",num+number];
        }];
        return cell;
    }
    return cell;
    
}


#pragma maark - dataSource
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    //判断是哪个tableview 分别设置数量
    if (tableView == self.newsView.newsNBATableView) {
        return [NewsHandle sharedNewsHandle].dataArray.count;
    }else
    {
        return [NewsHandle sharedNewsHandle].CBAarray.count;
    }
    
}
#pragma mark ---设置cell的高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //分别给tableview高度
    if (tableView == self.newsView.newsNBATableView) {
        return 400*LAYOUT_SIZE_HEIGHT;
    }else
    {
        return 400*LAYOUT_SIZE_HEIGHT;
    }
}

#pragma mark - 下拉刷新
- (void)updateData
{
    
    MJRefreshGifHeader *header = [MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(pullUpLoadData)];
    self.newsView.newsNBATableView.mj_header = header;
    [self.newsView.newsNBATableView.mj_header beginRefreshing];
    
}

-(void)updateCBA
{
    MJRefreshGifHeader *header = [MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(pullUpCBAData)];
    self.newsView.newsCBATableView.mj_header = header;
    [self.newsView.newsCBATableView.mj_header beginRefreshing];
    
}
#pragma mark - 下拉刷新方法
- (void)pullUpLoadData
{
    //重新加载数据
    [NewsHandle sharedNewsHandle].dataArray = nil;
    __weak typeof(self) weakself = self;
    [[NewsHandle sharedNewsHandle] getdataWithNPC:0 WithBlock:^(BOOL isFinished) {
        if (isFinished) {
            [weakself.newsView.newsNBATableView reloadData];
        }else{
            NSLog(@"数据加载失败");
        }
        [self.newsView.newsNBATableView.mj_header endRefreshing];
        
    }];
    
    
}

-(void)pullUpCBAData
{
    // 重新加载数据
    [NewsHandle sharedNewsHandle].CBAarray = nil;
    __weak typeof(self) weakself = self;
    [[NewsHandle sharedNewsHandle] getCBAdataNpc:0 WithBlock:^(BOOL isFinished) {
        
        if (isFinished) {
            [weakself.newsView.newsCBATableView reloadData];
        }else{
            NSLog(@"数据加载失败");
        }
        [self.newsView.newsCBATableView.mj_header endRefreshing];
        
    }];
    
}
#pragma mark - 上拉加载
- (void)addData1
{
    self.newsView.newsNBATableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        self.npcNumber++;
        __weak typeof(self) weakself = self;
        [[NewsHandle sharedNewsHandle] getdataWithNPC:self.npcNumber WithBlock:^(BOOL isFinished) {
            if (isFinished) {
                [weakself.newsView.newsNBATableView reloadData];
            }else{
                NSLog(@"数据加载失败");
            }
            
            [self.newsView.newsNBATableView.mj_footer endRefreshing];
        }];
    }];
    
    self.newsView.newsCBATableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        self.npcNumber++;
        __weak typeof(self) weakself = self;
        [[NewsHandle sharedNewsHandle] getCBAdataNpc:self.npcNumber WithBlock:^(BOOL isFinished) {
            
            if (isFinished) {
                [weakself.newsView.newsCBATableView reloadData];
            }else{
                NSLog(@"数据加载失败");
            }
            
            [self.newsView.newsCBATableView.mj_footer endRefreshing];
        }];
    }];
    
}

#pragma mark ---内存管理
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    [NewsHandle sharedNewsHandle].dataArray = nil;
    [NewsHandle sharedNewsHandle].CBAarray = nil;
}
#pragma mark ---点击选中状态
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.newsView.newsNBATableView) {
        //取消点击状态 模态出详情界面
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        NewsTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        self.model = [NewsHandle sharedNewsHandle].dataArray[indexPath.row];
        NewsShowViewController *showVC = [[NewsShowViewController alloc] init];
        //通过表明NEWS和ID找到对应的存储对象
        AVObject *object = [AVObject objectWithoutDataWithClassName:@"News" objectId:@"569f4004a633bd005b3767b4"];
        //每当数据保存的时候都进行数据更新保证获取到得数据是最新的
        object.fetchWhenSave = YES;
        //获取点击不同cell生成不同的Key值
        NSString *readCount = [NSString stringWithFormat:@"newsReadCount%ld",indexPath.row];
        //给点击的cell赋值
        [object setObject:[NSNumber numberWithInteger:1] forKey:readCount];
        //自动加1方法
        [object incrementKey:readCount];
        [object saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
            if (!error) {
                self.model.readCount = [[object objectForKey:readCount]integerValue];
                NSInteger readArts = [self.model.readarts integerValue];
                cell.readLabel.text = [NSString stringWithFormat:@"%ld",self.model.readCount + readArts];
            }
        }];
        showVC.model = self.model;
        UINavigationController *showNC = [[UINavigationController alloc] initWithRootViewController:showVC];
        showNC.modalPresentationStyle = 1;
        showNC.modalTransitionStyle = 1;
        [showNC setModalTransitionStyle:UIModalTransitionStyleFlipHorizontal];
        [self presentViewController:showNC animated:YES completion:nil];
    }else{
        //取消点击状态 模态出详情界面
        //569f4681a341310053f64ed4
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        NewsShowViewController *showVC = [[NewsShowViewController alloc] init];
        self.model = [NewsHandle sharedNewsHandle].CBAarray[indexPath.row];
        NewsTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        //通过表明NEWS和ID找到对应的存储对象
        AVObject *object = [AVObject objectWithoutDataWithClassName:@"CBANews" objectId:@"569f4681a341310053f64ed4"];
        //每当数据保存的时候都进行数据更新保证获取到得数据是最新的
        object.fetchWhenSave = YES;
        //获取点击不同cell生成不同的Key值
        NSString *readCount = [NSString stringWithFormat:@"newsReadCount%ld",indexPath.row];
        //给点击的cell赋值
        [object setObject:[NSNumber numberWithInteger:1] forKey:readCount];
        //自动加1方法
        [object incrementKey:readCount];
        [object saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
            if (!error) {
                self.model.readCount = [[object objectForKey:readCount]integerValue];
                NSInteger readArts = [self.model.readarts integerValue];
                cell.readLabel.text = [NSString stringWithFormat:@"%ld",self.model.readCount + readArts];
            }
        }];
        
        showVC.model = self.model;
        UINavigationController *showNC = [[UINavigationController alloc] initWithRootViewController:showVC];
        showNC.modalPresentationStyle = 1;
        showNC.modalTransitionStyle = 1;
        [showNC setModalTransitionStyle:UIModalTransitionStyleFlipHorizontal];
        [self presentViewController:showNC animated:YES completion:nil];
    }
    
    
    
    
}




@end
